using Microsoft.Extensions.Logging;
using SumerCoreDevOps.Domain.Entities;
using SumerCoreDevOps.Infrastructure.Data;

namespace SumerCoreDevOps.Infrastructure.ImageManagement;

/// <summary>
/// 镜像标签规则管理器
/// </summary>
public class ImageTagRuleManager
{
    private readonly FreeSQLProvider _dbProvider;
    private readonly ILogger<ImageTagRuleManager> _logger;

    public ImageTagRuleManager(FreeSQLProvider dbProvider, ILogger<ImageTagRuleManager> logger)
    {
        _dbProvider = dbProvider;
        _logger = logger;
    }

    /// <summary>
    /// 创建镜像标签规则
    /// </summary>
    public async Task<ImageTagRule> CreateRuleAsync(
        long workflowId,
        string name,
        string registryUrl,
        string projectName,
        string tagTemplate,
        string? defaultLanguage,
        string? environment,
        bool isDefault,
        string? createdBy)
    {
        var rule = new ImageTagRule
        {
            WorkflowId = workflowId,
            Name = name,
            RegistryUrl = registryUrl,
            ProjectName = projectName,
            TagTemplate = tagTemplate,
            DefaultLanguage = defaultLanguage,
            Environment = environment,
            IsDefault = isDefault,
            CreatedBy = createdBy,
            CreatedAt = DateTime.UtcNow,
            IsEnabled = true
        };

        await _dbProvider.Orm.Insert(rule).ExecuteAffrowsAsync();
        _logger.LogInformation("创建镜像标签规则: {Name}, 工作流 ID: {WorkflowId}", name, workflowId);

        return rule;
    }

    /// <summary>
    /// 更新镜像标签规则
    /// </summary>
    public async Task UpdateRuleAsync(
        long id,
        string name,
        string registryUrl,
        string projectName,
        string tagTemplate,
        string? defaultLanguage,
        string? environment,
        bool isDefault,
        bool isEnabled)
    {
        var rule = await _dbProvider.Orm.Select<ImageTagRule>()
            .Where(r => r.Id == id)
            .FirstAsync();

        if (rule == null)
        {
            throw new InvalidOperationException($"镜像标签规则 {id} 不存在");
        }

        rule.Name = name;
        rule.RegistryUrl = registryUrl;
        rule.ProjectName = projectName;
        rule.TagTemplate = tagTemplate;
        rule.DefaultLanguage = defaultLanguage;
        rule.Environment = environment;
        rule.IsDefault = isDefault;
        rule.IsEnabled = isEnabled;
        rule.UpdatedAt = DateTime.UtcNow;

        await _dbProvider.Orm.Update<ImageTagRule>()
            .SetSource(rule)
            .ExecuteAffrowsAsync();

        _logger.LogInformation("更新镜像标签规则: {Id}", id);
    }

    /// <summary>
    /// 删除镜像标签规则
    /// </summary>
    public async Task DeleteRuleAsync(long id)
    {
        await _dbProvider.Orm.Delete<ImageTagRule>()
            .Where(r => r.Id == id)
            .ExecuteAffrowsAsync();

        _logger.LogInformation("删除镜像标签规则: {Id}", id);
    }

    /// <summary>
    /// 根据工作流 ID 获取所有镜像标签规则
    /// </summary>
    public async Task<List<ImageTagRule>> GetRulesByWorkflowIdAsync(long workflowId)
    {
        return await _dbProvider.Orm.Select<ImageTagRule>()
            .Where(r => r.WorkflowId == workflowId)
            .OrderBy(r => r.CreatedAt)
            .ToListAsync();
    }

    /// <summary>
    /// 根据 ID 获取镜像标签规则
    /// </summary>
    public async Task<ImageTagRule?> GetRuleByIdAsync(long id)
    {
        return await _dbProvider.Orm.Select<ImageTagRule>()
            .Where(r => r.Id == id)
            .FirstAsync();
    }

    /// <summary>
    /// 获取工作流的默认镜像标签规则
    /// </summary>
    public async Task<ImageTagRule?> GetDefaultRuleByWorkflowIdAsync(long workflowId)
    {
        return await _dbProvider.Orm.Select<ImageTagRule>()
            .Where(r => r.WorkflowId == workflowId && r.IsDefault && r.IsEnabled)
            .FirstAsync();
    }

    /// <summary>
    /// 生成镜像标签
    /// </summary>
    public string GenerateImageTag(
        ImageTagRule rule,
        string? gitTag = null,
        string? commitSha = null,
        string? language = null,
        string? environment = null,
        int? buildNumber = null)
    {
        var tag = rule.TagTemplate;

        // 替换模板变量
        if (!string.IsNullOrEmpty(gitTag))
        {
            tag = tag.Replace("{git-tag}", gitTag);
        }

        if (!string.IsNullOrEmpty(commitSha))
        {
            var shortSha = commitSha.Length > 8 ? commitSha[..8] : commitSha;
            tag = tag.Replace("{commit-sha8}", shortSha);
            tag = tag.Replace("{commit-sha}", commitSha);
        }

        tag = tag.Replace("{lang}", language ?? rule.DefaultLanguage ?? "unknown");
        tag = tag.Replace("{env}", environment ?? rule.Environment ?? "default");

        if (buildNumber.HasValue)
        {
            tag = tag.Replace("{build-number}", buildNumber.Value.ToString());
        }

        tag = tag.Replace("{timestamp}", DateTime.UtcNow.ToString("yyyyMMddHHmmss"));

        // 生成完整镜像标签
        var fullTag = $"{rule.RegistryUrl}/{rule.ProjectName}:{tag}";

        return fullTag;
    }
}
